package com.zyl.pts.service.serviceImpl;

import com.zyl.pts.config.enums.CodeAndMessageEnum;
import com.zyl.pts.config.enums.ResultCode;
import com.zyl.pts.config.exception.ServiceException;
import com.zyl.pts.domain.bean.Account;
import com.zyl.pts.mapper.UserMapper;
import com.zyl.pts.service.UserService;
import com.zyl.pts.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;

/**
 * @version v1.0
 * @ProjectName: product_source
 * @Package: com.zyl.pts.service.serviceImpl
 * @ClassName: UserServiceImpl
 * @Description TODO(用户层实现类)
 * @Author 翟玉龙
 * @Date 2024/11/19-9:15
 */
@Service
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;

    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @return {@link Map }<{@link String }, {@link String }>
     */
    @Override
    public Map<String, String> login(String username, String password) {
        if(username == null || username.trim().isEmpty()) {
            throw new ServiceException(ResultCode.USERNAME_PARAMS_INVALID);
        }
        if(password == null || password.trim().isEmpty()) {
            throw new ServiceException(ResultCode.PASSWORD_PARAMS_INVALID);
        }

        Account user = userMapper.getUserByUserName(username, password);
        if(Objects.isNull(user)) {
            throw new ServiceException(ResultCode.USER_IS_NOT_EXIST);
        }

        // 进一步比较密码
        if(!password.equals(user.getPassword())) {
            throw new ServiceException(ResultCode.PASSWORD_INVALID);
        }

        // 判断用户状态
        if(user.getStatus() == 0) {
            throw new ServiceException(ResultCode.USER_IS_UNABLE);
        }

        // 根据用户数据签发token
        // 登陆成功返回token
        Map<String, Object> claims = Map.of("userName", user.getUsername(),
                "userId", user.getAccountId());
        String token = JwtUtil.sign(claims);
        return Map.of("token", token);
    }

    /**
     * 退出登录
     * @return {@link CodeAndMessageEnum }
     */
    @Override
    public CodeAndMessageEnum logout() {
        return CodeAndMessageEnum.SUCCESS;
    }

    /**
     * 获取用户信息
     * @param token token
     * @return {@link Account }
     */
    @Override
    public Account getUserInfo(String token) {
        /*
            获取用户id
         */
        String userID = JwtUtil.getValue(token, "userId", String.class);
        Account user = userMapper.getUserById(userID);
        if(user == null) {
            throw new ServiceException(ResultCode.USER_IS_NOT_EXIST);
        }
        return user;
    }
}
